<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use App\Models\Payment\PaymentOrder;

class CreatePaymentOrdersTable extends Migration
{

    const TABLE = PaymentOrder::TABLE;

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        !Schema::hasTable(self::TABLE) &&
        Schema::create(self::TABLE, function (Blueprint $table) {
            $table->uuid('id')->primary();
            $table->uuid('parking_lot_id')->default('');
            $table->uuid('related_id')->default('')->comment('订单ID');
            $table->string('related_type')->default('')->comment('订单类型');
            $table->string('order_title', 100)->default('')->comment('订单标题');
            $table->string('paid_code', 100)->default('')->unique()->comment('支付单号');
            $table->unsignedInteger('amount')->default(0)->comment('支付金额');
            $table->unsignedInteger('balance_amount')->default(0)->comment('抵扣余额');
            $table->unsignedInteger('point_amount')->default(0)->comment('抵扣积分');
            $table->unsignedInteger('frozen_balance_amount')->default(0)->comment('锁定余额');
            $table->unsignedInteger('frozen_point')->default(0)->comment('锁定积分');
            $table->dateTime('paid_at')->nullable()->comment('支付时间');
            $table->string('out_trade_no')->default('')->comment('支付平台交易单号');
            $table->string('pay_type', 50)->default('')->comment('支付方式');
            $table->string('trade_type', 50)->default('')->comment('发起支付方式');
            $table->string('order_status', 50)->default('')->comment('订单状态');
            $table->json('snapshot')->nullable()->comment('冗余信息');
            $table->boolean('had_invoiced')->default(false)->comment('是否已开票');
            $table->uuid('user_id')->default('')->comment('操作人ID');
            $table->string('user_name')->default('')->comment('操作人名称');
            $table->uuid('payment_channel_id')->default('')->comment('支付通道ID');
            $table->string('payer_id')->default('')->comment('支付人标识');
            $table->string('error')->default('')->comment('失败原因');
            $table->json('optional')->nullable()->comment('操作冗余');
            $table->timestamps();
            $table->index(['related_id', 'related_type'], 'idx_related_order');
            $table->index(['parking_lot_id', 'paid_code', 'paid_at', 'out_trade_no'], 'idx_parking_lot_id');
        });
        DB::statement("alter table `".self::TABLE."` comment '发起支付订单';");
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists(self::TABLE);
    }
}
